package gdufs.stat.service;

import gdufs.stat.service.vo.LoanInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class LibraryQuery {
	
	Log logger = LogFactory.getLog(LibraryQuery.class);
	
	private String endPoint = "http://opac.gdufs.edu.cn:8991/X?op=bor-info&cash=N&hold=N&bor_id=";

	public void setEndPoint(String endPoint) {
		this.endPoint = endPoint;
	}
	
	public List<LoanInfo> queryLoanInfo(String userId) throws HttpException, IOException, DocumentException, ParseException{
		List<LoanInfo> loanInfos = new ArrayList<LoanInfo>();
		String url = endPoint+userId;
		logger.debug("library query url:"+url);
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
		try{
			
			int statusCode = httpClient.executeMethod(getMethod);
			if(statusCode!=HttpStatus.SC_OK){
				System.err.println("查询借书信息失败，服务端返回HTTP代码："+statusCode);
				System.err.println(getMethod.getResponseBodyAsString());
			}else{
				InputStream is = getMethod.getResponseBodyAsStream();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "utf-8"));
		
				SAXReader reader = new SAXReader();
				Document document = reader.read(bufferedReader);
				List titles = document.selectNodes("//z13-title");
				List authors = document.selectNodes("//z13-author");
				List openDates = document.selectNodes("//z13-open-date");
				List updateDates = document.selectNodes("//z13-update-date");
				List dueDates = document.selectNodes("//due-date");
				List currentFines = document.selectNodes("//current-fine");
				
				Date today = DateUtils.truncate(new Date(), Calendar.DATE);
				for(int i=0; i<titles.size(); i++){
					LoanInfo loanInfo = new LoanInfo();
					loanInfo.setAuthor(((Node)authors.get(i)).getText());
					loanInfo.setCurrentFine(NumberUtils.toFloat(((Node)currentFines.get(i)).getText(),0));
					loanInfo.setDueDate(DateUtils.parseDate(((Node)dueDates.get(i)).getText(), new String[]{"yyyyMMdd"}));
					loanInfo.setOpenDate(DateUtils.parseDate(((Node)openDates.get(i)).getText(), new String[]{"dd/MM/yyyy"}));
					loanInfo.setTitle(((Node)titles.get(i)).getText());
					loanInfo.setUpdateDate(DateUtils.parseDate(((Node)updateDates.get(i)).getText(), new String[]{"dd/MM/yyyy"}));
					if(loanInfo.getDueDate().getTime()<=today.getTime()){
						loanInfo.setExpired(true);
					}
					
					logger.debug(loanInfo);
					loanInfos.add(loanInfo);
				}
				
			}
		}finally{
			getMethod.releaseConnection();
		}
		
		Collections.sort(loanInfos,new Comparator<LoanInfo>() {

			public int compare(LoanInfo o1, LoanInfo o2) {
				return (int) (o1.getDueDate().getTime()-o2.getDueDate().getTime());
			}
		});
		return loanInfos;
	}
}
